using UnityEngine;
using System.Collections;

public class CarAI : MonoBehaviour {
	
	/// <summary>
	/// Velocidade do carro.
 	public float velocity = 0;
	/// <summary>
	///Força de atrito com o chão.
	/// </summary>
	public float drag = 0.2f;
	/// <summary>
	/// A aceleração do carro.
	/// </summary>
	public float acceleration;
	/// <summary>
	/// Velocidade limite do carro.
	/// </summary>
	public int limit = 90;
	/// <summary>
	/// O Game Object que contém todos os waypoints.
	/// </summary>
	public GameObject waypointContainer;
	/// <summary>
	/// Array contendo todos os waypoints.
	/// </summary>
	public Transform[] waypoints = new Transform[77];
	/// <summary>
	/// Array contendo os possíveis waypoints, incluindo o container.
	/// </summary>
	private Transform[] potentialWaypoints;
	/// <summary>
	/// Waypoint atual.
	/// </summary>
	public int currentWaypoint = 0;
	/// <summary>
	/// A posição do waypoint relativa ao carro.
	/// </summary>
	private Vector3 relativeWaypointPosition;
	/// <summary>
	/// Contador para a mudança de aceleração.
	/// </summary>
	public float timer;
	private int i = 0;
			
	// Use this for initialization
	void Start () 
	{
		GetWaypoint();
		acceleration = Random.Range(0.2f,0.4f);
	}
	
	// Update is called once per frame
	void Update () 
	{
		timer += Time.deltaTime;
		
		if(timer >= 10)
		{
			acceleration = Random.Range(0.2f,0.4f);
			timer = 0;
		}
		
		transform.Translate(0,0,velocity*Time.deltaTime);
		NavigateToWaypoint();
		
		if(velocity < limit)
		{
			velocity += acceleration;
		}
		
		if(velocity > 0)
		{
			velocity -= drag;
		}
	}
	
	/// <summary>
	/// Define os waypoints por onde o carro irá percorrer.
	/// </summary>
	void GetWaypoint()
	{
		potentialWaypoints = waypointContainer.GetComponentsInChildren<Transform>();
		
		foreach(Transform potentialWaypoint in potentialWaypoints)
		{
			if(potentialWaypoint != waypointContainer.transform)
			{
				waypoints[i] = potentialWaypoint;
				i++;
			}
		}
	}
	
	/// <summary>
	/// Define para qual waypoint o carro navegará.
	/// </summary>
	void NavigateToWaypoint()
	{
		relativeWaypointPosition = transform.InverseTransformPoint(new Vector3(waypoints[currentWaypoint].position.x, transform.position.y, waypoints[currentWaypoint].position.z));
		
		transform.LookAt(new Vector3(waypoints[currentWaypoint].transform.position.x,transform.position.y,waypoints[currentWaypoint].transform.position.z));
		
		//Caso o carro esteja próximo do waypoint atual, ele passa para o próximo.
		if(relativeWaypointPosition.magnitude < 0.1)
		{
			currentWaypoint++;
		}
		
		//Ao chegar ao último waypoint, o carro recomeça o trajeto.
		if(currentWaypoint >= waypoints.Length)
		{
			currentWaypoint = 0;
		}
	}
}